package com.example.demo.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.bcel.classfile.Constant;
import org.apache.tomcat.util.codec.binary.Base64;

import com.example.demo.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtil {
	
	public static String createJWT(long ttlMillis, User user) {
		// 指定签名算法
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put("id", user.getId());
		claims.put("username", user.getUsername());
		 
		
		SecretKey key = generalKey();
		
		String subject = user.getUsername();
		
		JwtBuilder builder = Jwts.builder()
				.setClaims(claims)
				.setId(UUID.randomUUID().toString())
				.setIssuedAt(now)
				.setSubject(subject)
				.signWith(signatureAlgorithm, key);
		if(ttlMillis >= 0) {
			long expMillis = nowMillis + ttlMillis;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp);
		}
		return builder.compact();
	}
	
	/** Token的解密
	 * @param token
	 * @param user
	 * @return
	 */
	public static Claims parseJWT(String token, User user) {
		String key = user.getPassword();
		Claims claims = Jwts.parser()
				.setSigningKey(key)
				.parseClaimsJws(token).getBody();
		return claims;
	}
	
	/** 校验token
	 * 
	 * @param token
	 * @param user
	 * @return
	 */
	public static Boolean isVerify(String token, User user) {
		SecretKey key = generalKey();
		Claims claims = Jwts.parser()
				.setSigningKey(key)
				.parseClaimsJws(token).getBody();
		
		if(claims.get("username").equals(user.getUsername())) {
			return true;
		}
		return false;
	}
	
	 public static SecretKey generalKey(){
	        String stringKey ="7786df7fc3a34e26a61c034d5ec8245d"; //Constant.JWT_SECRET;//本地配置文件中加密的密文7786df7fc3a34e26a61c034d5ec8245d
	        byte[] encodedKey = Base64.decodeBase64(stringKey);//本地的密码解码[B@152f6e2
	        System.out.println(encodedKey);//[B@152f6e2
	        System.out.println(Base64.encodeBase64URLSafeString(encodedKey));//7786df7fc3a34e26a61c034d5ec8245d
	        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// 根据给定的字节数组使用AES加密算法构造一个密钥，使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。（后面的文章中马上回推出讲解Java加密和解密的一些算法）
	        return key;
	    }

}
